package cn.codergege.demo.controller

import cn.codergege.demo.entity.JsonData
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.util.*
import javax.servlet.http.HttpServletRequest

@Controller
@RequestMapping("/upload")
class UploadController {
    // windows 下
    val filePath = "F:\\tmp\\upload\\images\\"
//    val filePath = """F:\workspace\spring-stack-learning\spring2-demo-02-http-kotlin\src\main\resources\static\images\"""

   @GetMapping("/upload-page")
   fun uploadPage(): String {
      return "upload"
   }

   @PostMapping("/upload")
   @ResponseBody
   fun upload(
       @RequestParam("head_img")
       file: MultipartFile, // 接收 form 表单中 input type="file" 的文件.
       name: String, // 有 request, 这个可以忽略的.
       request: HttpServletRequest
   ): JsonData {
       println("file name: ${file.originalFilename}")
       println("name: $name")
       // 获取文件后缀名
       val suffix = file.originalFilename?.substringAfterLast(".")
       // 使用 uuid 重新生成文件名
       val fileName = UUID.randomUUID().toString() + "." + suffix
       println(fileName)
       // 保存路径
       val dest: File = File(filePath + fileName)
       try {
           file.transferTo(dest)
           return JsonData(0, dest.absolutePath, null)
       } catch (e: Exception) {
           println(e.message)
       }
       return JsonData(-1, fileName, "上传失败")
   }

}